package com.rongji.dfish.demo.intro.view;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.rongji.dfish.base.Page;
import com.rongji.dfish.demo.comm.service.CommService;
import com.rongji.dfish.demo.constant.DemoConstants;
import com.rongji.dfish.demo.entity.CommPost;
import com.rongji.dfish.demo.index.service.AnchorHelper;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.FrameworkHelper;
import com.rongji.dfish.framework.plugin.file.service.FileService;
import com.rongji.dfish.framework.plugin.file.ui.DefaultUploadFile;
import com.rongji.dfish.ui.Widget;
import com.rongji.dfish.ui.form.UploadItem;
import com.rongji.dfish.ui.layout.ButtonBar;
import com.rongji.dfish.ui.layout.FrameLayout;
import com.rongji.dfish.ui.layout.GridLayout;
import com.rongji.dfish.ui.layout.VerticalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.layout.grid.GridColumn;
import com.rongji.dfish.ui.layout.grid.Tr;
import com.rongji.dfish.ui.widget.Button;
import com.rongji.dfish.ui.widget.Html;
import com.rongji.dfish.ui.widget.Leaf;
import com.rongji.dfish.ui.widget.PageBar;
import com.rongji.dfish.ui.widget.TreePanel;

/**
 * 框架简介界面构建类
 * @author DFish Team
 */
public class IntroduceView {
	public static View buildIndexView(String anchor,String fromModule) {
		return buildIndexView(getMenuData(),anchor,fromModule);
	}
	public static View buildIndexView(List<Menu> menuList,String anchor,String fromModule) {
		View view = PubView.buildBodyView();
		//分为左右结构
		TreePanel menuTree = (TreePanel) view.findNodeById(PubView.BODY_MENU);

		
		VerticalLayout mainDisplay = (VerticalLayout) view.findNodeById(PubView.MAIN_DISPLAY);
		
		FrameLayout mainContent = new FrameLayout("mainContent");
		mainDisplay.add(mainContent);
		
		Menu focusMenu = null;
		String[] anchorInfo=AnchorHelper.getInstance().getAnchorInfo(anchor);
		if(anchorInfo==null||anchorInfo.length<2){
			anchorInfo=new String[]{fromModule,menuList.get(0).getMenuId()};
		}
		for (Menu menu : menuList) {
			Leaf leaf = new Leaf(menu.getMenuId(), menu.getMenuName());
			menuTree.add(leaf);
			if (menu.isOpenWindow()) {
				leaf.setOn(Leaf.EVENT_CLICK, "window.open('" + menu.getMenuAction() + "');");
			} else {
				String viewId = "v_" + menu.getMenuId();
				View contentView = new View(viewId).setSrc(menu.getMenuAction());
				mainContent.add(contentView);
				if(anchorInfo!=null&&anchorInfo.length>1&&menu.getMenuId() .equals(anchorInfo[1])){
					focusMenu=menu;
					leaf.setFocus(true);
				}
//				window.location.href='index.jsp#'+fromModule.substring(4)+"@file@"+viewId;
				leaf.setOn(Leaf.EVENT_CLICK, "window.location.href='index.jsp#" +fromModule+"@"+menu.getMenuId()+"';"+
						"this.cmd('clickMenu','" + menu.getMenuId() + "');");
			}
		}
//		if (focusMenu == null) {
//			focusMenu = menu;
//			leaf.setFocus(true);
//		}
//		fillMenus(bodyMenu, menuList);
		
		mainContent.setDft("v_" + focusMenu.getMenuId());
		
		//左边 结构树 +右边主面板
		
		//主面板被分为上下两部分，上边是 标题 和按钮栏栏
		//下边也别分为两个部分，左边是内容栏 右边是 结构树
	
		//内容栏分为标签页布局
		
		Html mainTitle = (Html) view.findNodeById(PubView.MAIN_TITLE);
		mainTitle.setText(focusMenu.getMenuName());
//		boolean disabled = "1".equals(category) && Utils.isEmpty(loginUser);
//		MenuCommand menu = new MenuCommand("");
		ButtonBar mainOper = (ButtonBar) view.findNodeById(PubView.MAIN_OPER);
		mainOper.add(new Button("", "刷新").setOn(Button.EVENT_CLICK, "VM(this).reload();"));
	
		
//		HorizontalLayout mainContentShell = new HorizontalLayout("m_content_shell");
//		mainDisplay.add(mainContentShell);
		
//		VerticalLayout mainContent = new VerticalLayout("m_content").setStyle("padding:10px;").setWmin(20).setHmin(20);
//		mainContentShell.add(mainContent);
		
//		Widget<?> introPage=getIntoContentPanel("intropage");
//		Widget<?> introProduct=getIntoContentPanel("introproduct"); 
//		Widget<?> components=new View("components").setSrc("components/index");
//		Widget<?> updates=getIntoContentPanel("updates"); 
//		Widget<?> sysinfo=new View("sysinfo").setSrc("pubInfo/sysinfo");
//		Widget<?> download=getIntoContentPanel("download"); 
//		Widget<?> links=getIntoContentPanel("links");
		
//		ButtonBar tabHead=new ButtonBar("main_bar");
//		tabHead.setPub(new Button(null).setCls("x-tab").setHmin(2));
//		mainContent.add(tabHead,"40");
//		tabHead.setCls("x-tabbar f-14").setFocusable(true);
//		//添加按钮
//		tabHead.add(new Button("产品概述").setId("btn_"+introProduct.getId()).setTarget(introProduct.getId()).setFocus(true));
//		tabHead.add(new Button("简介说明").setId("btn_"+introPage.getId()).setTarget(introPage.getId()));
//		tabHead.add(new Button("支持组件").setId("btn_"+components.getId()).setTarget(components.getId()));
//		tabHead.add(new Button("更新内容").setId("btn_"+updates.getId()).setTarget(updates.getId()));
//		tabHead.add(new Button("系统信息").setId("btn_"+sysinfo.getId()).setTarget(sysinfo.getId()));
//		tabHead.add(new Button("资料下载").setId("btn_"+download.getId()).setTarget(download.getId()));
		
//		FrameLayout film =new FrameLayout("main_film");
//		mainContent.add(film);
//		film.setDft(introProduct.getId());
//		film.add(introProduct);
//		film.add(introPage);
//		film.add(components);
//		film.add(updates);
//		film.add(sysinfo);
//		film.add(download);
		
//		Html tree=new Html("btn_"+links.getId(),FrameworkHelper.getFileText("m/demo/text/links.txt"));
//		
//		tree.setScroll(true).setCls("bg-low bd-mod bd-onlyleft").setWmin(1);
//		mainContentShell.add(tree,"240");

		view.addCommand("clickMenu", PubView.getAjaxCommand("intro/clickMenu?menuId=$0"));
		
		return view;
	}

	public static View buildInfoContentView(String textName) {
		View view = new View();
		VerticalLayout root=new VerticalLayout("root");
		root.setCls("download_info");
		view.add(root);
		
		VerticalLayout other=new VerticalLayout("");
		root.add(other,"-1");
		other.setMinheight(100);
		other.add(new Html("<div class='title'>相关资料下载</div>"));
		ButtonBar otherBtn=new ButtonBar("");
		otherBtn.setSpace(10).setStyle("margin-top:20px");
		other.add(otherBtn,"*");
		otherBtn.add(new Button("基础开发包").setOn(Button.EVENT_CLICK, "window.location.href='m/resource/dfish3_main.zip'"));
		otherBtn.add(new Button("DEMO包的源码").setOn(Button.EVENT_CLICK, "window.location.href='m/resource/dfish3_demo.zip'"));
		otherBtn.add(new Button("快速上手手册").setOn(Button.EVENT_CLICK, "window.location.href='m/resource/user_guide.docx'"));
		
		String pre="http://192.168.0.126:8081/nexus/service/local/repositories/dfish-release/content/com/rongji/";
		List<String[]> versions=Arrays.asList(new String[][]{{"1.0","3393","20170929"}});
		String[] jarNames=new String[]{"dfish-framework","dfish-ui","dfish-base","dfish-misc","dfish-uiplugin"};
		String[] jsNames=new String[]{"dfish-js-core","dfish-js-pl"};
		String[] apiNames=new String[]{"dfish-api-java","dfish-api-js"};
		Map<String,String[]> nameMap=new LinkedHashMap<String,String[]>();
		nameMap.put("jar包", jarNames);
		nameMap.put("JS", jsNames);
		nameMap.put("API", apiNames);
		
		VerticalLayout downloadPanel= new VerticalLayout("");
		root.add(downloadPanel);
		
		List<String[]> data=null;
		for(String[] ver:versions){
			data=new ArrayList<String[]>();
			StringBuilder format=null;
			String link="";
			String t=ver[0];
			String v=ver[1];
			String date=ver[2];
			downloadPanel.add(new Html("<div class='title'>版本"+t+"<span><span>|</span>更新日期："+date+"</span></div>"),"100");
			for(Entry<String, String[]> entry:nameMap.entrySet()){
				format=new StringBuilder("");
				for(String name:entry.getValue()){
						link=pre+name+"/3.0."+v+"-"+date+"/"+name+"-"+"3.0."+v+"-"+date;
						if ("jar包".equals(entry.getKey())) {
							link+=".jar";
						}
						else {
							link+=".zip";
						}
						format.append("<a href='"+link+"'>["+name+"]</a>&nbsp;");
				}
				data.add(new String[]{entry.getKey(),format.toString()});
			}
			GridLayout layout=new GridLayout("").setCls("d_grid");
			downloadPanel.add(layout,"-1");
			layout.getColumns().add(GridColumn.text("vName", "10").setAlign(GridColumn.ALIGN_CENTER));
			layout.getColumns().add(GridColumn.text("vLink", "100"));
			for(String[] r:data){
				Tr contRow=new Tr();
				layout.add(contRow);
				contRow.setData("vName", r[0]);
				contRow.setData("vLink", r[1]);
			}
		}
		
		return view;
	}

	public static View buildUpdatesView(Page page) {
		View view = PubView.buildBodyView();
		CommService commService = FrameworkHelper.getBean(CommService.class);
		List<CommPost> commPosts=commService.findCommPosts(page,DemoConstants.COMM_BBFB);
		VerticalLayout verticalLayout =new VerticalLayout("ver").setScroll(true);
		verticalLayout.setStyle("padding:20px;");
		VerticalLayout updateContent =new VerticalLayout("ver1");
		FileService fileService=FrameworkHelper.getBean(FileService.class);
		List<String> postIds = new ArrayList<String>();
		for(CommPost comm:commPosts) {
			postIds.add(comm.getPostId());
		}
		Map<String, List<UploadItem>> map = fileService.findUploadItems(DemoConstants.FILE_LINK_COMM, postIds);
		for(CommPost comm:commPosts){
			updateContent.add(new Html("", comm.getPostTitle()).setStyle("font-size:16px"), "-1");
			updateContent.add(new Html("", comm.getPostContent()).setWidth(VerticalLayout.ALIGN_CENTER), "-1");	
			//下载附件
			List<UploadItem> fileItems=map.get(comm.getPostId());
			if(fileItems==null){
				updateContent.add(new Html("暂无附件").setStyle("color:gray"),"-1");
			}else{
			updateContent.add(
					new DefaultUploadFile("attachFile","发帖附件")
					.setUploadItems(fileItems)
					.setReadonly(true)
					, "-1");
			}
			updateContent.add(new Html("<hr style='border:1px dashed #CCC'/>"), "-1");		
		}
		verticalLayout.add(updateContent);
		PageBar pageBar = buildPageBar(page).setSrc("intro/reloadText?cp=$0&textName=updates&comm=1");
		verticalLayout.add(pageBar);
		view.add(verticalLayout);
		return view;
	}
	private static PageBar buildPageBar(Page page) {
		PageBar pageBar=new PageBar("pageBar",PageBar.TYPE_TEXT);
		pageBar.setBtncount(5).setAlign(PageBar.ALIGN_RIGHT).setHeight(50)
		.setWidth("95%").setNofirstlast(false).setJump(true);
		PubView.fillPagePanel(pageBar, page);
		return pageBar;
	}
	private static Widget<?> buildInfoContentPanel(String textName) {
		return new Html(FrameworkHelper.getFileText("m/intro/html/"+textName+".htm")).setScroll(true);
	}
	public static class Menu {
		private String menuId;
		private String menuName;
		private String menuAction;
		// 打开新窗口
		private boolean openWindow;
		
		public Menu() {
			
		}
		
		public Menu(String menuId, String menuName, String menuAction, boolean openWindow) {
	        super();
	        this.menuId = menuId;
	        this.menuName = menuName;
	        this.menuAction = menuAction;
	        this.openWindow = openWindow;
        }
		
		public String getMenuId() {
			return menuId;
		}
		
		public void setMenuId(String menuId) {
			this.menuId = menuId;
		}
		
		public String getMenuName() {
			return menuName;
		}
		
		public void setMenuName(String menuName) {
			this.menuName = menuName;
		}
		
		public String getMenuAction() {
			return menuAction;
		}
		
		public void setMenuAction(String menuAction) {
			this.menuAction = menuAction;
		}

		public boolean isOpenWindow() {
			return openWindow;
		}

		public void setOpenWindow(boolean openWindow) {
			this.openWindow = openWindow;
		}
	}
	
	public static List<Menu> getMenuData() {
		List<Menu> menuData = new ArrayList<Menu>();
//		menuData.add(new Menu( "overview", "产品概述", "intro/reloadText?textName=overview", false ));
		menuData.add(new Menu( "introduction", "简介说明", "intro/reloadText?textName=introduction", false ));
		menuData.add(new Menu( "components", "支持组件", "components/index", false ));
//		menuData.add(new Menu( "docs", "文档规范", "intro/reloadText?textName=docs", false ));
//		menuData.add(new Menu( "updates", "更新内容", "intro/reloadText?textName=updates", false )); // 更新内容可能放到社区中心去
//		menuData.add(new Menu( "sysinfo", "系统信息", "pubInfo/sysinfo", false ));
//		menuData.add(new Menu( "downloads", "资料下载", "intro/reloadText?textName=downloads", false ));
		menuData.add(new Menu( "jsAPI", "JavaScript API", "api/api.html", true ));
		menuData.add(new Menu( "javaAPI", "Java API", "api/java/index.html", true ));
		return menuData;
	}
	
	public static List<Menu> getDownloadMenuData() {
		List<Menu> menuData = new ArrayList<Menu>();
		menuData.add(new Menu( "updates", "更新内容", "intro/reloadText?textName=updates", false )); // 更新内容可能放到社区中心去
		menuData.add(new Menu( "downloads", "资料下载", "intro/reloadText?textName=downloads", false ));
		menuData.add(new Menu( "error", "错误查看", "exceptionViewer/showAsLog", false ));
		return menuData;
	}

	public static View buildDownloadView( String anchor,String fromModule) {
		return buildIndexView(getDownloadMenuData(),anchor,fromModule);
	}

}
